package org.agile4j.rpc.common.utils;

import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

/**
 * 属性文件工具类
 * 
 * @author hanyx
 */
public final class PropsUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(PropsUtil.class);

	/**
	 * 加载属性文件
	 * @param fileName 文件名
	 * @return
	 */
	public static Properties loadProps(String fileName) {
		Resource resource = new ClassPathResource(fileName);
		Properties properties = null;
		try {
			properties = PropertiesLoaderUtils.loadProperties(resource);
		} catch (IOException e) {
			LOGGER.error("load properties file failure", e);
		}
		return properties ;
	}
	
	/**
	 * 获取字符类属性(默认值为 空字符串)
	 */
	public static String getString(Properties props, String key) {
		return getString(props, key, "") ;
	}
	
	/**
	 * 获取字符型属性(可指定默认值)
	 */
	public static String getString(Properties props, String key, String defaultValue) {
		String value = defaultValue ;
		if(props.containsKey(key)) {
			value = props.getProperty(key) ;
		}
		return value ;
	}
	
	/**
	 * 获取数值类型属性(默认值为 0)
	 */
	public static int getInt(Properties props, String key) {
		return getInt(props, key, 0) ;
	}
	
	/**
	 * 获取数值类型属性(可指定默认值)
	 */
	public static int getInt(Properties props, String key, int defaultValue) {
		int value = defaultValue ;
		if(props.containsKey(key)) {
			value = Integer.valueOf(props.getProperty(key)) ;
		}
		return value ;
	}
	
	/**
	 * 获取布尔类型属性(默认值为 false)
	 */
	public static boolean getBoolean(Properties props, String key) {
		return getBoolean(props, key, false) ;
	}
	
	/**
	 * 获取布尔类型属性(可指定默认值)
	 */
	public static boolean getBoolean(Properties props, String key, boolean defaultValue) {
		boolean value = defaultValue ;
		if(props.containsKey(key)) {
			value = Boolean.valueOf(props.getProperty(key)) ;
		}
		return value ;
	}
}
